package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.pojo.ChartCategoryDTO;
import com.xbongbong.paas.pojo.ChartSaveRuleDTO;
import com.xbongbong.paas.pojo.PkChartPojo;
import com.xbongbong.paas.pojo.PkSetPojo;
import com.xbongbong.paas.pojo.dto.ChartSetDetailDTO;
import com.xbongbong.paas.pojo.dto.ChartSetEnableDTO;
import com.xbongbong.paas.pojo.dto.ChartSetSaveDTO;
import com.xbongbong.paas.pojo.dto.PkChartListDTO;
import com.xbongbong.paas.pojo.vo.ChartSaveRuleVO;
import com.xbongbong.paas.pojo.vo.ChartSetVO;
import com.xbongbong.paas.pojo.vo.PkChartListVO;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.service.PkSetService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.companyconfig.pojo.CompanyConfigEnablePojo;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigHasBeenEnableBatchDTO;
import com.xbongbong.pro.companyconfig.pojo.vo.CompanyConfigHasBeenEnableBatchVO;
import com.xbongbong.pro.domain.entity.ChartCategoryEntity;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.StatisticsServicesErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.PkErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.service.toolbox.statistic.help.ChartPkRuleHelp;
import com.xbongbong.pro.statistic.enums.ChartCategoryTypeEnum;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.enums.SystemCodeEnum;
import com.xbongbong.pro.statistic.model.ChartCategoryModel;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.model.ChartModel;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.help.AppModuleHelp;
import com.xbongbong.saas.help.MarketManagementBusinessHelp;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author youli.chen
 * @version v1.0
 * @ProjectName xbb-pro
 * @Description: TODO
 * @date 2019/1/21 13:47
 * @since v1.0
 */
@Service("pkSetService")
public class PkSetServiceImpl implements PkSetService {

    private static final Logger LOG = LoggerFactory.getLogger(PkSetServiceImpl.class);

    @Resource
    private ChartModel chartModel;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private ChartCategoryModel chartCategoryModel;
    @Resource
    private ChartPkRuleHelp chartPkRuleHelp;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private AppModuleHelp appModuleHelp;
    @Resource
    private MarketManagementBusinessHelp marketManagementBusinessHelp;
    @Resource
    private ChartCustomModel chartCustomModel;

    /**
     * 【web】获取PK榜设置
     *
     * @param chartSetDetailDTO
     * @return
     * @throws XbbException
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<ChartSetVO> getChartSet(ChartSetDetailDTO chartSetDetailDTO) throws XbbException {
        ChartSetVO chartSetVO = new ChartSetVO();
        // 鉴权
        Set<String> permSet = chartSetDetailDTO.getLoginUser().getPermSet();
        if (permSet == null || !permSet.contains(ProPermissionAliasEnum.CHART_VIEW.getAlias())) {
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224070);
        }
        // 新建按钮权限，目前只有自定义pk由后端控制
        JSONObject permissionObj = new JSONObject();
        if (permSet.contains(ProPermissionAliasEnum.CHART_ADD.getAlias())) {
            permissionObj.put(ProPermissionAliasEnum.CHART_ADD.getAlias(), true);
        }
        chartSetVO.setChartPermissions(permissionObj);

        List<PkChartPojo> pkChartPojoList = new ArrayList<>();
        String corpid = chartSetDetailDTO.getCorpid();
        PkChartListDTO pkChartListDTO = new PkChartListDTO();
        BeanUtil.copyProperties(chartSetDetailDTO, pkChartListDTO);
        // 获取pk指标数据
        PkChartListVO pkChartListVO = getPkChartList(pkChartListDTO);
        List<ChartEntity> pkChartList = pkChartListVO.getPkChartList();
        //判断套餐版本."标准版"是不能拥有“市场管理”相关的指标(eg： 线索分析)
        boolean standardWithFeeType = marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(corpid);
        if(pkChartList.size() > 0) {
            // PK榜设置数据封装
            for (ChartEntity chartEntity : pkChartList) {
                //标准版不能设置"市场管理"的PK指标
                if(standardWithFeeType && SystemCodeEnum.PK_CLUE_CONVERSION_RATE.getSystemCode().equals(chartEntity.getSystemCode())){
                    continue;
                }
                PkChartPojo pkChartPojo = new PkChartPojo();
                pkChartPojo.setChartId(chartEntity.getId());
                pkChartPojo.setName(chartEntity.getName());
                pkChartPojo.setOldName(chartEntity.getOldName());
                pkChartPojo.setMemo(chartEntity.getMemo());
                if (chartEntity.getEnable() != null) {
                    pkChartPojo.setEnable(chartEntity.getEnable().equals(BasicConstant.IS_USE));
                }

                JSONArray joinRule = chartEntity.getJoinRule();
                JSONArray removeRule = chartEntity.getRemoveRule();
                JSONArray scopeRule = chartEntity.getScopeRule();
                // 参与人
                List<OptionalRangeEntity> joinRuleData = new ArrayList<>();
                if(joinRule != null){
                    try {
                        joinRuleData = joinRule.toJavaList(OptionalRangeEntity.class);
                    } catch (JSONException e) {
                        joinRuleData = new ArrayList<>();
                    }
                }
                pkChartPojo.setJoinRule(joinRuleData);

                // 不参与人
                List<OptionalRangeEntity> removeRuleData = new ArrayList<>();
                if(removeRule != null){
                    try {
                        removeRuleData = removeRule.toJavaList(OptionalRangeEntity.class);
                    } catch (JSONException e) {
                        removeRuleData = new ArrayList<>();
                    }
                }
                pkChartPojo.setRemoveRule(removeRuleData);

                // 可见权限
                List<OptionalRangeEntity> scopeData = new ArrayList<>();
                if(scopeRule != null){
                    try {
                        scopeData = scopeRule.toJavaList(OptionalRangeEntity.class);
                    } catch (JSONException e) {
                        scopeData = new ArrayList<>();
                    }
                }
                pkChartPojo.setScopeRule(scopeData);

                // 权限类型
                pkChartPojo.setPowerType(chartEntity.getPowerType());

                pkChartPojoList.add(pkChartPojo);
            }
        }

        chartSetVO.setPkChartList(pkChartPojoList);


        // 公司配置数据（是否显示为0空数据、是否显示离职员工）
        List<String> aliasList = Arrays.asList(CompanyConfigEnum.PK_NULL_DATA.getAlias(), CompanyConfigEnum.PK_LEAVE.getAlias());
        CompanyConfigHasBeenEnableBatchDTO batchDTO = new CompanyConfigHasBeenEnableBatchDTO();
        BeanUtil.copyProperties(chartSetDetailDTO, batchDTO);
        batchDTO.setAliasList(aliasList);
        // 没有数据时，使用默认值
        CompanyConfigHasBeenEnableBatchVO batchVO;
        try {
            batchVO = companyConfigService.hasBeenEnableBatch(batchDTO);
        } catch (XbbException e) {
            // 添加默认值
            batchVO = new CompanyConfigHasBeenEnableBatchVO();
            List<CompanyConfigEnablePojo> configList = new ArrayList<>();
            CompanyConfigEnablePojo pojo1 = new CompanyConfigEnablePojo(CompanyConfigEnum.PK_NULL_DATA.getAlias(),
                    Integer.parseInt(CompanyConfigEnum.PK_NULL_DATA.getValue()));
            CompanyConfigEnablePojo pojo2 = new CompanyConfigEnablePojo(CompanyConfigEnum.PK_LEAVE.getAlias(),
                    Integer.parseInt(CompanyConfigEnum.PK_LEAVE.getValue()));
            configList.add(pojo1);
            configList.add(pojo2);
            batchVO.setList(configList);
        }
        List<CompanyConfigEnablePojo> configList = batchVO.getList();
        // 是否显示为0空数据封装
        List<PkSetPojo> pkSetPojoList = new ArrayList<>();
        for(int i = 0; i < configList.size(); i++) {
            CompanyConfigEnablePojo enablePojo = configList.get(i);
            CompanyConfigEnum configEnum = CompanyConfigEnum.getByAlias(enablePojo.getAlias());
            PkSetPojo setPojo = new PkSetPojo();
            setPojo.setDataId(i + 1L);
            setPojo.setAlias(enablePojo.getAlias());
            setPojo.setEnable(Objects.equals(BasicConstant.IS_USE, enablePojo.getEnable()));
            setPojo.setName(configEnum.getName());

            pkSetPojoList.add(setPojo);
        }

        chartSetVO.setDataSetList(pkSetPojoList);
        chartSetVO.setPageHelper(pkChartListVO.getPageHelper());

        return new XbbResponse<>(chartSetVO);
    }

    /**
     * 【web】启用/关闭pk榜指标
     *
     * @param chartSetEnableDTO
     * @return
     * @throws XbbException
     * @version v1.0
     * @since v1.0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public XbbResponse<Integer> chartSetEnable(ChartSetEnableDTO chartSetEnableDTO) throws XbbException {
        Integer chartSetId;

        // TODO PK榜设置的权限
        // 记录日志
        String corpid = chartSetEnableDTO.getCorpid();
        String userId = chartSetEnableDTO.getUserId();
        Long chartId = chartSetEnableDTO.getChartId();
        // 登录用户
        String loginUserName = chartSetEnableDTO.getLoginUserName();
        // 系统or自定义
        boolean custom = Objects.equals(chartSetEnableDTO.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode());
        // 开启pk榜
        if (chartSetEnableDTO.getEnable()) {
            if (Objects.equals(StatisticsTypeEnum.CUSTOM_STATISTIC.getCode(), chartSetEnableDTO.getStatisticsType())) {
                // 判断是否超过套餐数量
                Integer status = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.CUSTOM_CHART_NUM, BasicConstant.ONE);
                if(!Objects.equals(status, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(status, PackageStatusEnum.WARNING.getCode())){
                    throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224031);
                }
            }
        }
        // 关闭pk榜时，判断已启用的数量
        if (!chartSetEnableDTO.getEnable()) {
            PkChartListDTO pkChartListDTO = new PkChartListDTO();
            BeanUtil.copyProperties(chartSetEnableDTO, pkChartListDTO);
            pkChartListDTO.setEnable(EnableEnum.OPEN.getCode());
            PkChartListVO pkChartListVO = getPkChartList(pkChartListDTO);
            List<ChartEntity> pkChartList = pkChartListVO.getPkChartList();
            if (pkChartList.size() == 0) {
                throw new XbbException(PkErrorCodeEnum.API_ERROR_901002);
            } else if (pkChartList.size() == 1 && !custom) {
                ChartEntity enableEntity = pkChartList.get(0);
                if(enableEntity.getId().equals(chartSetEnableDTO.getChartId())) {
                    throw new XbbException(PkErrorCodeEnum.API_ERROR_901002);
                }
            }
        }
        // 自定义图表和系统图表区分，默认走系统
        ChartEntity chartEntity;
        if (custom) {
            chartEntity = chartCustomModel.getByKey(chartId, corpid);
        } else {
            chartEntity = chartModel.getByKey(chartId, corpid);
        }
        if (chartEntity != null) {
            if (Objects.equals(EnableEnum.transformEnable2Bool(chartEntity.getEnable()), chartSetEnableDTO.getEnable())) {
                // 如果指标开启状态无需更改，返回0，让前端刷新页面
                return new XbbResponse<>(BasicConstant.ZERO);
            }
            // 同步更新报表分类表
            chartEntity.setEnable(chartSetEnableDTO.getEnable() ? BasicConstant.IS_USE : BasicConstant.NO_USE);
            chartEntity.setDel(DelEnum.NORMAL.getDel());
            try {
                if (custom) {
                    chartSetId = chartCustomModel.update(chartEntity);
                } else {
                    chartSetId = chartModel.update(chartEntity);
                }
                // 设置分类开启/关闭
                setCategoryEnable(chartSetEnableDTO, chartEntity);
            } catch (Exception e) {
                LOG.error("【web】启用/关闭pk榜指标时：Chart数据库更新pk榜设置出错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            // 日志
            String memo;
            OperateTypeEnum operateTypeEnum;
            if (chartSetEnableDTO.getEnable()) {
                operateTypeEnum = OperateTypeEnum.ENABLE;
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_OPEN_PK), loginUserName, chartEntity.getName());
            } else {
                operateTypeEnum = OperateTypeEnum.CLOSE;
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CLOSE_PK), loginUserName, chartEntity.getName());
            }
            mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.PK, operateTypeEnum, chartEntity.getId().toString(),
                    chartEntity.getName(), memo, chartSetEnableDTO.getHttpHeader());
        } else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
        }

        return new XbbResponse<>(chartSetId);
    }
    
    @Override
    public void setCategoryEnable(BaseDTO baseDTO, ChartEntity chartEntity) throws XbbException {
        String corpid = baseDTO.getCorpid();
        Integer chartType = chartEntity.getChartType();
        ChartCategoryDTO chartCategoryDTO = new ChartCategoryDTO(chartEntity);
        BeanUtil.copyProperties(baseDTO, chartCategoryDTO);
        List<ChartCategoryEntity> getChartCategoryList = getAllCategoryList(chartCategoryDTO);
        if(!getChartCategoryList.isEmpty()){
            List<Long> categoryIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            // 自定义pk和自定义目标管理只需要把首页和图表中心原始的分类id放进去就行
            if (Objects.equals(chartType, ChartTypeEnum.CUSTOMER_PERFORMANCE.getCode()) || Objects.equals(chartType, ChartTypeEnum.PK_CUSTOM.getCode())) {
                for (ChartCategoryEntity chartCategoryEntity : getChartCategoryList) {
                    if (Objects.equals(chartCategoryEntity.getType(), ChartCategoryTypeEnum.WEB_INDEX_LEFT.getCode()) 
                            ||Objects.equals(chartCategoryEntity.getType(), ChartCategoryTypeEnum.PK_CUSTOM.getCode())
                            ||Objects.equals(chartCategoryEntity.getType(), ChartCategoryTypeEnum.PERFORMANCE_CUSTOM.getCode())) {
                        categoryIdIn.add(chartCategoryEntity.getId());
                    }
                }
            } else {
                getChartCategoryList.forEach(item -> categoryIdIn.add(item.getId()));
            } 
            // 更新enable
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid", corpid);
            params.put("enable", chartEntity.getEnable());
            params.put("idIn", categoryIdIn);
            chartCategoryModel.batchUpdateEnable(params);
        }
    }

    @Override
    public List<ChartCategoryEntity> getAllCategoryList(ChartCategoryDTO chartCategoryDTO) throws XbbException {
        ChartEntity chartEntity = chartCategoryDTO.getChartEntity();
        String corpid = chartEntity.getCorpid();
        JSONArray categoryArr = chartEntity.getCategory();
        List<Integer> typeIn = chartCategoryDTO.getTypeIn();
        if (CollectionUtils.isEmpty(typeIn)) {
            typeIn = ChartCategoryTypeEnum.getCodeList4All();
            Integer webLeftCategoryType = ChartCategoryTypeEnum.WEB_INDEX_LEFT.getCode();
            typeIn.remove(webLeftCategoryType);
            typeIn.remove(ChartCategoryTypeEnum.PERFORMANCE.getCode());
        }
        List<ChartCategoryEntity> getChartCategoryList = new ArrayList<>();
        if(categoryArr != null && !categoryArr.isEmpty()){
            List<Long> chartCategoryIdIn = categoryArr.toJavaList(Long.class);
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("typeIn", typeIn);
            param.put("idIn", chartCategoryIdIn);
            getChartCategoryList = chartCategoryModel.findEntitys(param);
        }
        return getChartCategoryList;
    }

    /**
     * 【web】保存指标名称
     *
     * @param chartSetSaveDTO
     * @return
     * @throws XbbException
     * @version v1.0
     * @since v1.0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public XbbResponse<Integer> saveName(ChartSetSaveDTO chartSetSaveDTO) throws XbbException {
        // TODO PK榜设置的权限
        // 记录日志
        String corpid = chartSetSaveDTO.getCorpid();
        String userId = chartSetSaveDTO.getUserId();
        // 登录用户
        String loginUserName = chartSetSaveDTO.getLoginUserName();

        Integer chartSetId;
        ChartEntity getChartPkByKey;
        // 自定义图表和系统图表区分，默认走系统
        boolean custom = Objects.equals(chartSetSaveDTO.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode());
        if (custom) {
            getChartPkByKey = chartCustomModel.getByKey(chartSetSaveDTO.getChartId(), corpid);
        } else {
            getChartPkByKey = chartModel.getByKey(chartSetSaveDTO.getChartId(), corpid);
        }
        if (getChartPkByKey != null) {
            ChartEntity updateChart = new ChartEntity();
            BeanUtils.copyProperties(getChartPkByKey, updateChart);
            updateChart.setName(chartSetSaveDTO.getName());
            updateChart.setDel(DelEnum.NORMAL.getDel());
            try {
                if (custom) {
                    chartSetId = chartCustomModel.update(updateChart);
                    // 把分类名称也更新
                    ChartCategoryDTO chartCategoryDTO = new ChartCategoryDTO(getChartPkByKey);
                    chartCategoryDTO.setTypeIn(Arrays.asList(ChartCategoryTypeEnum.PK_CUSTOM.getCode()));
                    List<ChartCategoryEntity> categoryList4Pk = getAllCategoryList(chartCategoryDTO);
                    if (CollectionsUtil.isNotEmpty(categoryList4Pk)) {
                        ChartCategoryEntity chartCategoryEntity = categoryList4Pk.get(0);
                        chartCategoryEntity.setName(chartSetSaveDTO.getName());
                        chartCategoryModel.update(chartCategoryEntity);
                    }
                } else {
                    chartSetId = chartModel.update(updateChart);
                }
            } catch (Exception e) {
                LOG.error("【web】更改pk榜指标名称时：Chart数据库更新pk榜设置出错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            // 日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_PK), loginUserName, chartSetSaveDTO.getName());
            mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.PK, OperateTypeEnum.EDIT,
                    getChartPkByKey.getId().toString(), chartSetSaveDTO.getName(), memo, chartSetSaveDTO.getHttpHeader());
        } else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
        }
        return new XbbResponse<>(chartSetId);
    }

    /**
     * 【web】保存PK榜设置
     *
     * @param chartSaveRuleDTO
     * @return
     * @throws XbbException
     */
    @Override
    public XbbResponse<ChartSaveRuleVO> saveRule(ChartSaveRuleDTO chartSaveRuleDTO) throws XbbException {
        ChartSaveRuleVO chartSaveRuleVO = new ChartSaveRuleVO();
        String corpid = chartSaveRuleDTO.getCorpid();
        List<OptionalRangeEntity> joinRule = chartSaveRuleDTO.getJoinRule();
        List<OptionalRangeEntity> removeRule = chartSaveRuleDTO.getRemoveRule();
        List<OptionalRangeEntity> scopeRule = chartSaveRuleDTO.getScopeRule();

        if(joinRule.isEmpty()){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nMessageUtil.getMessage(MessageConstant.PK_JOINRULE_NOT_NULL));
        }
        if(scopeRule.isEmpty()){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nMessageUtil.getMessage(MessageConstant.PK_SCOPERULE_NOT_NULL));
        }

        JSONArray joinRuleArr = JSONArray.parseArray(JSON.toJSONString(joinRule));
        JSONArray removeRuleArr = removeRule.isEmpty() ? new JSONArray() : JSONArray.parseArray(JSON.toJSONString(removeRule));
        JSONArray scopeRuleArr = JSONArray.parseArray(JSON.toJSONString(scopeRule));

        Integer powerType = chartSaveRuleDTO.getPowerType();

        ChartEntity getChartPkByKey = chartModel.getByKey(chartSaveRuleDTO.getId(), corpid);
        if(getChartPkByKey != null){
            getChartPkByKey.setJoinRule(joinRuleArr);
            getChartPkByKey.setRemoveRule(removeRuleArr);
            getChartPkByKey.setScopeRule(scopeRuleArr);
            getChartPkByKey.setPowerType(powerType);
            chartModel.update(getChartPkByKey);
        }
        return new XbbResponse<>(chartSaveRuleVO);
    }

    /**
     * 获取PK榜设置项
     *
     * @param pkChartListDTO
     * @return PkChartListVO
     * @throws XbbException
     * @version v1.0
     * @since v1.0
     */
    private PkChartListVO getPkChartList(PkChartListDTO pkChartListDTO) throws XbbException {
        PkChartListVO pkChartListVO = new PkChartListVO();
        List<ChartEntity> pkChartList = new ArrayList<>(0);
        PageHelper pageHelper = new PageHelper();
        try {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", pkChartListDTO.getCorpid());
            param.put("statisticsType", pkChartListDTO.getStatisticsType());
            param.put("del", DelEnum.NORMAL.getDel());
            if(pkChartListDTO.getEnable() != null) {
                param.put("enable", pkChartListDTO.getEnable());
            }
            if(pkChartListDTO.getNameLike() != null) {
                param.put("nameLike", pkChartListDTO.getNameLike());
            }
            if (Objects.equals(pkChartListDTO.getStatisticsType(), StatisticsTypeEnum.SYSTEM_STATISTIC.getCode())) {
                param.put("chartType", ChartTypeEnum.PK.getCode());
                pageHelper = PageHelperUtil.getPageHelper(param, chartModel, pkChartListDTO.getPage(), pkChartListDTO.getPageSize());
                pkChartList = (List<ChartEntity>) PageHelperUtil.getEntityList(param, pageHelper, chartModel);
            } else if (Objects.equals(pkChartListDTO.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                param.put("chartType", ChartTypeEnum.PK_CUSTOM.getCode());
                pageHelper = PageHelperUtil.getPageHelper(param, chartCustomModel, pkChartListDTO.getPage(), pkChartListDTO.getPageSize());
                pkChartList = (List<ChartEntity>) PageHelperUtil.getEntityList(param, pageHelper, chartCustomModel);
            }
        } catch (Exception e) {
            LOG.error("Chart或ChartCustom数据表获取pk榜设置列表出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        // 公司pk榜默认配置初始化
        chartPkRuleHelp.initPkSetRule(pkChartList, pkChartListDTO.getCorpid());

        pkChartListVO.setPkChartList(pkChartList);
        pkChartListVO.setPageHelper(pageHelper);
        return pkChartListVO;
    }
}
